//
//  WHWebViewController.m
//  LvZhongMagicKey
//
//  Created by 邓伟浩 on 2018/5/30.
//  Copyright © 2018年 邓伟浩. All rights reserved.
//

#import "WHWebViewController.h"
#import "YYKit.h"
#import "WHJSHandle.h"

@interface WHWebViewController ()<WKNavigationDelegate, WKUIDelegate>

/** 上次进度条位置 */
@property (nonatomic, assign) double lastProgress;
@property (nonatomic,strong) WHJSHandle *jsHandler;

@end

@implementation WHWebViewController

- (instancetype)initWithUrl:(NSString *)url {
    if (self = [super init]) {
        self.url = url;
        _progressViewColor = [UIColor redColor];
    }
    return self;
}

- (void)setUrl:(NSString *)url {
    if (_url != url) {
        _url = url;
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:_url]];
        [self.webView loadRequest:request];
    }
}

- (void)setProgressViewColor:(UIColor *)progressViewColor {
    _progressViewColor = progressViewColor;
    _progressView.tintColor = progressViewColor;
}

- (void)viewDidLoad {
    [super viewDidLoad];

//    self.edgesForExtendedLayout = UIRectEdgeTop;
    [self initWKWebView];

    //适配iOS11
    if (@available(iOS 11.0, *)){
        self.webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
}

#pragma mark ———— 初始化WKWebView ————
- (void)initWKWebView {
    WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
    configuration.preferences.javaScriptEnabled = YES; //打开js交互
    _webConfiguration = configuration;

    _jsHandler = [[WHJSHandle alloc] initWithViewController:self configuration:configuration];

    self.webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, kTopHeight, KScreenWidth, KScreenHeight-kTopHeight) configuration:configuration];
    _webView.navigationDelegate = self;
    _webView.UIDelegate = self;
    _webView.backgroundColor = [UIColor clearColor];
    _webView.allowsBackForwardNavigationGestures = YES; //打开网页间的 滑动返回
    _webView.scrollView.decelerationRate = UIScrollViewDecelerationRateNormal;

    //监控进度
    [_webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    [self.view addSubview:_webView];

    //进度条
    _progressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
    _progressView.tintColor = _progressViewColor;
    _progressView.trackTintColor = [UIColor clearColor];
    _progressView.frame = CGRectMake(0, kTopHeight, KScreenWidth, 3.0);
    [self.view addSubview:_progressView];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:_url]];
    [_webView loadRequest:request];
}

#pragma mark ———— 进度条 ————
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {

    [self updateProgress:_webView.estimatedProgress];
}

#pragma mark ———— 更新进度条 ————
- (void)updateProgress:(double)progress{
    self.progressView.alpha = 1;
    if(progress > _lastProgress){
        [self.progressView setProgress:self.webView.estimatedProgress animated:YES];
    } else {
        [self.progressView setProgress:self.webView.estimatedProgress];
    }
    _lastProgress = progress;

    if (progress >= 1) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            self.progressView.alpha = 0;
            [self.progressView setProgress:0];
            _lastProgress = 0;
        });
    }
}

#pragma mark ———— WKUIDelegate ————

- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable))completionHandler {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:prompt message:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.text = defaultText;
    }];
    [alertController addAction:([UIAlertAction actionWithTitle:@"完成" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(alertController.textFields[0].text?:@"");
    }])];
    
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:([UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler();
    }])];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler {
    
    [WHView showAlertwithTitle:@"提示" message:message?:@"" okAction:^(UIAlertAction *action) {
        completionHandler(YES);
    } cancelAction:^(UIAlertAction *action) {
        completionHandler(NO);
    }];
}


#pragma mark ———— WKNavigationDelegate ————
/** 加载完毕 */
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    if (self.navigationItem.title == nil) {
        self.navigationItem.title = webView.title;
    }
    [self updateProgress:webView.estimatedProgress];

    [self updateNavigationItems];
}

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    if(webView != self.webView) {
        decisionHandler(WKNavigationActionPolicyAllow);
        return;
    }
    // 更新返回按钮
    [self updateNavigationItems];

    NSURL *tmp = navigationAction.request.URL.absoluteURL;
    UIApplication *app = [UIApplication sharedApplication];
    if ([tmp.scheme isEqualToString:@"tel"]) {
        if ([app canOpenURL:tmp]) {
            [app openURL:tmp];
            decisionHandler(WKNavigationActionPolicyCancel);
            return;
        }
    }

    if ([tmp.scheme isEqualToString:@"jump"] || [tmp.scheme isEqualToString:@"answerpass"] || [tmp.scheme isEqualToString:@"updateaccountmoney"]) {
        [self handleNavigationAction:navigationAction];

        decisionHandler(WKNavigationActionPolicyCancel);
        return;
    }


    decisionHandler(WKNavigationActionPolicyAllow);
}

- (void)handleNavigationAction:(WKNavigationAction *)navigationAction {

}

- (void)updateNavigationItems {

}

- (void)backBtnClicked {
    [self.webView stopLoading];
    if ([self.webView canGoBack]) {
        [self.webView goBack];
    }else{
        [super backBtnClicked];
    }
}

- (void)dealloc {
    [_jsHandler cancelHandler];
    self.webView.navigationDelegate = nil;
    [_webView removeObserver:self forKeyPath:@"estimatedProgress"];
}

@end
